package util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;

import db.DBConnection;
import db.DBSQLUtil;

/**
 * A little support class for more comfort in debugging the engine.
 * 
 * @author Kristin Behrens, Robin Gawenda, Swen Jung
 */
public class ConsoleHelper extends MyLogger implements Runnable {
	Thread thread = null;

	/**
	 * Instantiates the ConsoleHelper with references to {@link FileManager},
	 * {@link DownloadManager} and {@link engineServer}.
	 * 
	 * @param f
	 * @param d
	 * @param s
	 * @param webServer
	 */
	public ConsoleHelper() {
		thread = new Thread(this);
		//thread.setDaemon(true);
		thread.start();
	}

	public void run() {
		boolean run = true;
		String answer="SELECT * FROM user;";
		BufferedReader test = new BufferedReader(new InputStreamReader(
				System.in));
		while (run) {
			try {
				System.out.println(answer);
				answer = test.readLine();
				if(answer.equals("/q"))run=false;
				else tryStatement(answer);
			} catch (StringIndexOutOfBoundsException e) {
				System.out.println("Please type at least one character!");
			} catch (Exception e) {
				log.throwing(sourceClass, "run", e);
			}
		}
		DBConnection.shutdown();
	}

	public void tryStatement(String stmt) {
		ResultSet rs = null;
		try {
			rs = DBConnection.getConnection().createStatement().executeQuery(
					stmt);
			DBSQLUtil.printResultSet(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
